/**
 * SCRM 对接
 * https://ll64kbqo4j.feishu.cn/docx/BVKIdQ3Sjo2n3mxFxrYcM33tntd
 */
import { getLogger, Service } from '@gnlab/utils'
import { type Observable, Subject, filter } from 'rxjs'
import {
  inSCRM,
  type SCRMMessage,
  listenSCRMMessage,
  sendToSCRM,
  confirmSCRMStatus,
} from '@/lib/scrm'
import { type Services } from '@/services'

export { type SCRMMessage }

const logger = getLogger('services/scrm')

const messageSubject = new Subject<SCRMMessage>()
const message$ = messageSubject.asObservable()
function initReceive() {
  listenSCRMMessage(message => {
    logger.info('receive', message)
    messageSubject.next(message)
  })
}

export class SCRM extends Service<Services> {
  private get account() {
    return this.services.auth.account$.value
  }

  registered() {
    initReceive()
  }

  readonly inSCRM = inSCRM

  readonly message$ = message$

  // 监听指定类型的消息
  // observable 会被缓存，保证同一个 type 多次获取，返回的是同一个 observable（例如可以安全用于 useEffect()）
  message<T>(type: string) {
    if (!this.observableCache.has(type)) {
      const observable = this.message$.pipe(
        filter((message): message is SCRMMessage<T> => message.type === type),
      )
      this.observableCache.set(type, observable)
    }
    return this.observableCache.get(type)! as Observable<SCRMMessage<T>>
  }
  private readonly observableCache = new Map<string, Observable<unknown>>()

  send = sendToSCRM

  async confirmStatus() {
    const token = this.account?.token ?? ''
    return confirmSCRMStatus(token)
  }
}
